/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require("mongoose");
var DataCollection = require("../models/goods.model");
var CommitCollection = require("../models/commits.model");
const async = require("async");


//数据存储
exports.create = function (req,res,next) {
	console.log(req.body)
	const dataColl = new DataCollection(req.body);
	dataColl.save().then(data=>{
		res.json(data)
	})
}

//获取一个对象
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findById(id,(err,data)=>{
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
		res.json(data);
	})
}

//删除
exports.remove = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findByIdAndRemove(id,(err,data)=>{
		res.json(data);
	})
}

//分页查询
exports.list = function (req,res,next) {
	var page = req.body.page ? req.body.page : 1;
	var rows = req.body.rows ? req.body.rows : 10;
	console.log(req.body)
	var queryCondition = {};
    if(req.body._id && req.body._id.length>0){
        queryCondition = {
            cateId:{$in:req.body._id.split(",")}
		};
	}
	if(req.body.title && req.body.title.trim().length>0){
		title = req.body.title,
		queryCondition = {
			"title":new RegExp(title,'i'),
		}
	}
	DataCollection.paginate(queryCondition, {sort:{_id:-1},page: parseInt(page), limit: parseInt(rows)}, (err, result)=>{

		async.map(result.docs,(news,callback)=>{
			CommitCollection.count({newsID:news._id},(err,count)=>{
				if(err){
					return ;
				}else{
					news.comNum = count;
					console.log(news);
					callback(null,news)
				}
			})
		},(err,data)=>{
			result.rows = result.docs;
			delete result.docs;
			// console.log(result)
			res.json(result);
		})

		
	});
}
//列出全部的
exports.listOne = function (req,res,next) {
	var page = req.body.page ? req.body.page : 1;
	var rows = req.body.rows ? req.body.rows : 10;
	var queryCondition = {};
	DataCollection.paginate(queryCondition, {sort:{_id:-1},page: parseInt(page), limit: parseInt(rows)}, (err, result)=>{
		result.rows = result.docs;
		delete result.docs;

		res.json(result)
	});
}


//删除多个删除
exports.removes = function (req,res,next) {
	var ids = req.body.ids;
	// console.log(ids)
	// var len = ids.length;
	// console.log(len);
	if(ids.length>0){
		console.log(ids);
		DataCollection.remove({_id:{$in:ids.split(",")}}).then((err,data)=>{
			res.json({"msg":"deletes success","status":200})
		})
	}else{
		res.json({"msg":"deletes fail","status":404})
	}
}

//删除cateId的新闻
exports.delCateId = function(req,res,next){
	var cateId = req.body.cateId;
	console.log(cateId)
	DataCollection.remove({cateId:cateId},(err,data)=>{
		res.json(data);
	})
}
